<template>
  <Dialog
    v-model="dialogVisible"
    width="1002px"
    maxHeight="550px"
    :before-close="() => clearForm(formRef)"
    :title="index === 1 ? '新增地址' : '编辑地址'"
    class="mobile-dialog"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" class="mobile-form">
      <div :class="isMobile ? '' : 'flex'">
        <el-form-item label="" prop="first_name">
          <el-input
            v-model="form.first_name"
            :placeholder="t('dealerAssetManagement.checkouts.firstName')"
            clearable
            style="width: 304px !important; height: 40px !important"
            maxlength="128"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="" prop="last_name">
          <el-input
            v-model="form.last_name"
            :placeholder="t('dealerAssetManagement.checkouts.lastName')"
            clearable
            style="width: 304px !important; height: 40px !important"
            maxlength="128"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="" prop="zip_code">
          <el-input
            v-model="form.zip_code"
            :placeholder="t('dealerAssetManagement.checkouts.zipCode')"
            clearable
            style="width: 304px !important; height: 40px !important"
          />
        </el-form-item>
      </div>
      <div :class="isMobile ? '' : 'flex'">
        <el-form-item label="" prop="country_id">
          <el-select-v2
            v-model="form.country_id"
            :teleported="false"
            :placeholder="t('dealerAssetManagement.checkouts.country')"
            filterable
            :props="selectProps"
            :options="countryOptions"
            size="large"
            :style="
              isMobile
                ? 'width: 100% !important'
                : stateOptions.length
                  ? 'width: 304px !important'
                  : 'width: 460px !important'
            "
            @change="handleChangeCountry"
          />
        </el-form-item>
        <el-form-item label="" prop="state_id" v-if="stateOptions.length">
          <el-select-v2
            v-model="form.state_id"
            :placeholder="t('dealerAssetManagement.checkouts.state')"
            filterable
            :props="selectProps"
            :options="stateOptions"
            size="large"
            :style="
              isMobile
                ? 'width: 100% !important'
                : stateOptions.length
                  ? 'width: 304px !important'
                  : 'width: 460px !important'
            "
            @change="handleChangeState"
          />
        </el-form-item>
        <el-form-item label="" prop="city_id">
          <el-select-v2
            v-model="form.city_id"
            :placeholder="t('dealerAssetManagement.checkouts.city')"
            filterable
            allow-create
            :props="selectProps"
            :options="cityOptions"
            size="large"
            :style="
              isMobile
                ? 'width: 100% !important'
                : stateOptions.length
                  ? 'width: 304px !important'
                  : 'width: 460px !important'
            "
          />
        </el-form-item>
      </div>
      <el-form-item label="" prop="address">
        <el-input
          v-model="form.address"
          :placeholder="t('dealerAssetManagement.checkouts.address')"
          clearable
          style="height: 40px !important"
        />
      </el-form-item>
      <el-form-item label="" prop="address2">
        <el-input
          v-model="form.address2"
          :placeholder="t('dealerAssetManagement.checkouts.address2')"
          clearable
          style="height: 40px !important"
        />
      </el-form-item>
      <el-form-item label="" prop="company">
        <el-input
          v-model="form.company"
          :placeholder="t('dealerAssetManagement.checkouts.company')"
          clearable
          style="height: 40px !important"
        />
      </el-form-item>
      <div class="flex">
        <el-form-item label="" prop="phone">
          <el-input
            v-model="form.phone"
            :placeholder="t('dealerAssetManagement.checkouts.phone')"
            clearable
            style="width: 460px !important; height: 40px !important"
          />
        </el-form-item>
        <el-form-item label="" prop="email">
          <el-input
            v-model="form.email"
            :placeholder="t('dealerAssetManagement.checkouts.email')"
            clearable
            style="width: 460px !important; height: 40px !important"
          />
        </el-form-item>
      </div>
      <div class="m-l-10px m-b-10px">{{ t('dealerAssetManagement.checkouts.phoneAvoid') }}</div>
      <el-form-item label="" prop="remark">
        <el-input
          v-model="form.remark"
          :placeholder="t('dealerAssetManagement.checkouts.tax')"
          clearable
          style="height: 40px !important"
        />
      </el-form-item>
      <div class="m-l-10px m-b-10px">{{ t('dealerAssetManagement.checkouts.taxAvoid') }}</div>
      <el-form-item label="">
        <el-checkbox
          v-model="form.is_default"
          :disabled="index === 2 && row.is_default === 1"
          :true-label="1"
          :false-label="0"
          :label="t('dealerAssetManagement.checkouts.saveAsDefault')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="mobile-button-group horizontal">
        <el-button class="m-r-4px" @click="clearForm(formRef)">
          {{ t('system.parameterConfig.cancel') }}
        </el-button>
        <el-button type="primary" @click="submitForm(formRef)">
          {{ t('dealerAssetManagement.checkouts.save') }}
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import {
  createAddressInfoApi,
  editAddressInfoApi,
  getAreaEnumApi,
  getCountryEnumApi
} from '@/api/order'
import type { FormInstance, FormRules } from 'element-plus'

const props = withDefaults(defineProps<{ index: number | null; row?: any }>(), {
  index: null,
  row: () => ({})
})
const { index } = toRefs(props)

const emits = defineEmits(['refresh'])

const { t } = useI18n()

// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)
const dialogVisible = ref<boolean>(false)
const formRef = ref()
const form = ref<Record<string, any>>({
  first_name: '',
  last_name: '',
  zip_code: '',
  country_id: null,
  city_id: null,
  state_id: null,
  address: '',
  address2: '',
  company: '',
  phone: '',
  email: '',
  remark: '',
  is_default: 0
})
const customerId = ref<string | number>()
const countryOptions = ref<any[]>([])
const cityOptions = ref<any[]>([])
const stateOptions = ref<any[]>([])
const cityOptionsCopy = ref<any[]>([])

const selectProps = ref({
  label: 'name',
  value: 'id'
})
const rules = ref<FormRules>({
  first_name: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.firstNameValidation'),
      trigger: 'change'
    }
  ],
  last_name: [
    {
      required: false,
      message: t('dealerAssetManagement.checkouts.lastNameValidation'),
      trigger: 'change'
    }
  ],
  zip_code: [
    {
      required: false,
      message: t('dealerAssetManagement.checkouts.zipCodeValidation'),
      trigger: 'change'
    }
  ],
  country_id: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.countryValidation'),
      trigger: 'change'
    }
  ],
  city_id: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.cityValidation'),
      trigger: 'change'
    }
  ],
  state_id: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.stateValidation'),
      trigger: 'change'
    }
  ],
  address: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.addressValidation'),
      trigger: 'change'
    }
  ],
  phone: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.phoneValidation'),
      trigger: 'change'
    }
  ],
  email: [
    {
      required: false, // 取消必填，改为可选字段
      trigger: ['change', 'blur'],
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          // 只有填写了值才进行校验
          const reg =
            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
          if (reg.test(value)) {
            callback() // 校验通过
          } else {
            callback(new Error(t('dealerAssetManagement.checkouts.emailValidationMsg'))) // 校验失败
          }
        } else {
          callback() // 未填写值，直接通过校验
        }
      }
    }
  ]
})

//根据国家查询另外市和州的数据
const handleChangeCountry = async (val: string) => {
  form.value.state_id = null
  form.value.city_id = null
  setTimeout(() => {
    formRef.value.clearValidate()
  })
  const resp = await getAreaEnumApi({ country_id: val })

  if (!resp.data.state.length) {
    stateOptions.value = resp.data.state
    cityOptions.value = resp.data.city
    cityOptionsCopy.value = []
  } else {
    stateOptions.value = resp.data.state
    cityOptionsCopy.value = resp.data.city
    cityOptions.value = []
  }
}
//根据州/省的id过滤出市/区的数据
const handleChangeState = (val: string | number) => {
  return new Promise((resolve) => {
    form.value.city_id = null
    setTimeout(() => {
      formRef.value.clearValidate()
    })
    cityOptions.value = cityOptionsCopy.value.filter(
      (item: Record<string, any>) => item.state_id == val
    )
    resolve(true)
  })
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(form.value))
      params.user_id = customerId.value
      // delete params.state_id
      if (typeof params.city_id == 'number') {
        params.city_name = null
      } else {
        params.city_name = params.city_id
        params.city_id = null
      }
      if (params.state_id) {
        params.state =
          stateOptions.value.find((item: any) => item.id == params.state_id)?.name || ''
      }
      if (index.value === 1) {
        const resp = await createAddressInfoApi(params)
        if (resp.code === 0) {
          ElMessage.success('新增地址成功')
          clearForm(formEl)
          emits('refresh')
        }
      } else {
        params.id = props.row.id
        const resp = await editAddressInfoApi(params)
        if (resp.code === 0) {
          ElMessage.success('更新地址成功')
          clearForm(formEl)
          emits('refresh')
        }
      }
    }
  })
}
const clearForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    first_name: '',
    last_name: '',
    zip_code: '',
    country_id: null,
    city_id: null,
    state_id: null,
    address: '',
    address2: '',
    company: '',
    phone: '',
    email: '',
    remark: '',
    is_default: 0
  } as any
  formEl.resetFields()
  dialogVisible.value = false
}

const dropDownBoxQuery = async (userId: string | number) => {
  customerId.value = userId
  backShow()
}
//回显
const backShow = async () => {
  if (index.value !== 1) {
    form.value.first_name = props.row.first_name
    form.value.last_name = props.row.last_name
    form.value.zip_code = props.row.zip_code
    form.value.address = props.row.address
    form.value.address2 = props.row.address2
    form.value.company = props.row.company
    form.value.phone = props.row.phone
    form.value.email = props.row.email
    form.value.remark = props.row.remark
    form.value.is_default = props.row.is_default
    form.value.country_id = props.row.country_id
    await handleChangeCountry(props.row.country_id)
    form.value.state_id = props.row.state_id ? props.row.state_id.toString() : null
    if (props.row.state_id) await handleChangeState(props.row.state_id)
    form.value.city_id = props.row.city_id ? props.row.city_id : props.row.city_name
  }
}
onMounted(async () => {
  const resp = await getCountryEnumApi()
  countryOptions.value = resp.data
})
defineExpose({ dialogVisible, backShow, dropDownBoxQuery })
</script>

<style lang="less" scoped>
:deep(.el-form-item) {
  margin-right: 10px;
}

:deep(.el-input__inner) {
  height: 40px !important;
}
</style>
